package com.store.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.store.common.Result;
import com.store.dto.OrderCreateRequest;
import com.store.service.OrderService;
import com.store.vo.OrderVO;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 订单控制器
 */
@Slf4j
@RestController
@RequestMapping("/order")
@RequiredArgsConstructor
public class OrderController {
    
    private final OrderService orderService;
    
    /**
     * 创建订单（从购物车结算）
     */
    @PostMapping("/create")
    public Result<Long> createOrder(@Validated @RequestBody OrderCreateRequest orderRequest,
                                     HttpServletRequest request) {
        try {
            Long userId = getUserId(request);
            Long orderId = orderService.createOrder(userId, orderRequest);
            return Result.success("订单创建成功", orderId);
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return Result.error("创建订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询订单列表（分页）
     */
    @GetMapping("/list")
    public Result<IPage<OrderVO>> getOrderList(@RequestParam(defaultValue = "1") int page,
                                                 @RequestParam(defaultValue = "10") int pageSize,
                                                 HttpServletRequest request) {
        try {
            Long userId = getUserId(request);
            IPage<OrderVO> orderPage = orderService.getOrderList(userId, page, pageSize);
            return Result.success(orderPage);
        } catch (Exception e) {
            log.error("查询订单列表失败", e);
            return Result.error("查询订单列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取订单详情
     */
    @GetMapping("/{id}")
    public Result<OrderVO> getOrderDetail(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long userId = getUserId(request);
            OrderVO order = orderService.getOrderDetail(userId, id);
            return Result.success(order);
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return Result.error("获取订单详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 取消订单
     */
    @PutMapping("/{id}/cancel")
    public Result<String> cancelOrder(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long userId = getUserId(request);
            orderService.cancelOrder(userId, id);
            return Result.success("订单已取消");
        } catch (Exception e) {
            log.error("取消订单失败", e);
            return Result.error("取消订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员/员工查询所有订单列表（分页+筛选）
     */
    @GetMapping("/admin/list")
    public Result<IPage<OrderVO>> getAdminOrderList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            HttpServletRequest request) {
        try {
            IPage<OrderVO> orderPage = orderService.getAdminOrderList(page, pageSize, orderNo, status, startDate, endDate);
            return Result.success(orderPage);
        } catch (Exception e) {
            log.error("查询订单列表失败", e);
            return Result.error("查询订单列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员/员工查看订单详情（无权限限制）
     */
    @GetMapping("/admin/{id}")
    public Result<OrderVO> getAdminOrderDetail(@PathVariable Long id, HttpServletRequest request) {
        try {
            OrderVO order = orderService.getAdminOrderDetail(id);
            return Result.success(order);
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return Result.error("获取订单详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员/员工发货
     */
    @PutMapping("/{id}/ship")
    public Result<String> shipOrder(@PathVariable Long id, HttpServletRequest request) {
        try {
            orderService.shipOrder(id);
            return Result.success("订单已发货");
        } catch (Exception e) {
            log.error("订单发货失败", e);
            return Result.error("订单发货失败：" + e.getMessage());
        }
    }
    
    /**
     * 顾客确认收货
     */
    @PutMapping("/{id}/receive")
    public Result<String> receiveOrder(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long userId = getUserId(request);
            orderService.receiveOrder(userId, id);
            return Result.success("确认收货成功");
        } catch (Exception e) {
            log.error("确认收货失败", e);
            return Result.error("确认收货失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员/员工完成订单
     */
    @PutMapping("/{id}/complete")
    public Result<String> completeOrder(@PathVariable Long id, HttpServletRequest request) {
        try {
            orderService.completeOrder(id);
            return Result.success("订单已完成");
        } catch (Exception e) {
            log.error("完成订单失败", e);
            return Result.error("完成订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 从请求中获取用户ID
     */
    private Long getUserId(HttpServletRequest request) {
        Object userIdObj = request.getAttribute("userId");
        if (userIdObj == null) {
            throw new RuntimeException("未登录或登录已过期");
        }
        return Long.valueOf(userIdObj.toString());
    }
}


